/**
 * RTSP播放器模拟实现
 * 
 * 注意：此文件仅用于演示目的。在实际项目中，应使用专门的RTSP流播放库，
 * 如JSMpeg、hls.js配合RTSP转HLS、或WebRTC等解决方案。
 */

class RtspPlayer {
    constructor(container, options = {}) {
        this.container = typeof container === 'string' ? document.querySelector(container) : container;
        this.options = Object.assign({
            autoplay: true,
            muted: true,
            controls: true // 启用内置控制器以方便调试
        }, options);
        
        this.isPlaying = false;
        this.videoElement = null;
        
        this._initPlayer();
    }
    
    _initPlayer() {
        // 清空容器
        this.container.innerHTML = '';
        
        // 创建视频元素
        this.videoElement = document.createElement('video');
        this.videoElement.style.width = '100%';
        this.videoElement.style.height = '100%';
        this.videoElement.autoplay = this.options.autoplay;
        this.videoElement.muted = this.options.muted;
        this.videoElement.controls = this.options.controls;
        
        // 添加事件监听
        this.videoElement.addEventListener('playing', () => {
            console.log('Video playing event fired');
            this.isPlaying = true;
            this._triggerEvent('playing');
        });
        
        this.videoElement.addEventListener('error', (e) => {
            console.error('Video error:', this.videoElement.error);
            this.isPlaying = false;
            this._handleError('Video playback error: ' + (this.videoElement.error ? this.videoElement.error.message : 'unknown error'));
        });
        
        // 添加到DOM
        this.container.appendChild(this.videoElement);
    }
    
    connect(url) {
        console.log('Connecting to URL:', url);
        
        // 重置状态
        this.stop();
        
        // 显示加载状态
        this.container.innerHTML = '<div style="padding: 20px; text-align: center;">连接中...</div>';
        this._initPlayer();
        
        // 使用一个可靠的示例视频
        const videoUrl = 'https://www.w3schools.com/html/mov_bbb.mp4';
        console.log('Using video URL:', videoUrl);
        
        try {
            // 简单直接地设置视频源并播放
            this.videoElement.src = videoUrl;
            
            this.videoElement.oncanplay = () => {
                console.log('Video can play');
                this.isPlaying = true;
                this._triggerEvent('playing');
            };
            
            // 尝试播放
            const playPromise = this.videoElement.play();
            if (playPromise !== undefined) {
                playPromise.catch(error => {
                    console.error('Autoplay prevented:', error);
                    // 在页面上显示手动播放按钮
                    this._showPlayButton();
                });
            }
        } catch (error) {
            console.error('Connection error:', error);
            this._handleError('连接错误: ' + error.message);
        }
        
        return true;
    }
    
    _showPlayButton() {
        // 创建播放按钮覆盖层
        const playButton = document.createElement('div');
        playButton.style.position = 'absolute';
        playButton.style.top = '0';
        playButton.style.left = '0';
        playButton.style.right = '0';
        playButton.style.bottom = '0';
        playButton.style.display = 'flex';
        playButton.style.justifyContent = 'center';
        playButton.style.alignItems = 'center';
        playButton.style.backgroundColor = 'rgba(0,0,0,0.5)';
        playButton.style.cursor = 'pointer';
        
        const playIcon = document.createElement('div');
        playIcon.innerHTML = '▶';
        playIcon.style.color = 'white';
        playIcon.style.fontSize = '48px';
        
        playButton.appendChild(playIcon);
        this.container.appendChild(playButton);
        
        // 点击播放
        playButton.addEventListener('click', () => {
            this.videoElement.play()
                .then(() => {
                    // 播放成功后移除按钮
                    this.container.removeChild(playButton);
                })
                .catch(err => {
                    console.error('Manual play failed:', err);
                });
        });
    }
    
    stop() {
        if (this.videoElement) {
            this.videoElement.pause();
            this.videoElement.removeAttribute('src');
            this.videoElement.load(); // 清空缓存的视频
            this.isPlaying = false;
        }
    }
    
    toggleFullscreen() {
        if (!this.videoElement) return;
        
        if (document.fullscreenElement) {
            document.exitFullscreen();
        } else {
            this.videoElement.requestFullscreen().catch(err => {
                console.error('Fullscreen request failed:', err);
            });
        }
    }
    
    takeSnapshot() {
        if (!this.videoElement || !this.isPlaying) {
            console.error('Cannot take snapshot: video not playing');
            return null;
        }
        
        try {
            const canvas = document.createElement('canvas');
            canvas.width = this.videoElement.videoWidth;
            canvas.height = this.videoElement.videoHeight;
            
            const ctx = canvas.getContext('2d');
            ctx.drawImage(this.videoElement, 0, 0, canvas.width, canvas.height);
            
            return canvas.toDataURL('image/png');
        } catch (error) {
            console.error('Snapshot error:', error);
            return null;
        }
    }
    
    _handleError(message) {
        console.error('Player error:', message);
        this.isPlaying = false;
        
        // 显示错误消息
        this.container.innerHTML = `
            <div style="padding: 20px; color: red; text-align: center;">
                <strong>Error:</strong> ${message}
                <br><br>
                <button id="retry-connection">重试</button>
            </div>
        `;
        
        // 添加重试按钮功能
        const retryBtn = this.container.querySelector('#retry-connection');
        if (retryBtn) {
            retryBtn.addEventListener('click', () => {
                this.connect(this.lastUrl);
            });
        }
        
        this._triggerEvent('error', { message });
    }
    
    _triggerEvent(name, data = {}) {
        const event = new CustomEvent(`rtsp:${name}`, {
            detail: { player: this, ...data }
        });
        this.container.dispatchEvent(event);
    }
}

// 将RtspPlayer导出为全局变量，以便于使用
window.RtspPlayer = RtspPlayer;
